package com.yxhl.zoume.core.car.fragment.common;


import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.custom.QuickIndexBar;
import com.yxhl.zoume.common.ui.custom.QuicklyClearEditText;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.car.model.CarSelectPassengerEntity;
import com.yxhl.zoume.core.car.presenter.AlphabetSearchPresenter;
import com.yxhl.zoume.core.officialcar.activity.CallCarForOthersActivity;
import com.yxhl.zoume.core.car.adapter.CarSelectPassengerAdapter;
import com.yxhl.zoume.core.car.view.common.AlphabetSearchView;
import com.yxhl.zoume.di.component.car.DaggerOfficialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.alphabet.AlphabetHelper;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnTextChanged;
import jp.wasabeef.recyclerview.animators.SlideInUpAnimator;

/**
 * created by sugarya 16/08/16
 * 替他人叫车 选择乘车人页面
 */
public class CarSelectPassengerFragment extends BaseFragment implements AlphabetSearchView<CarSelectPassengerEntity> {

    private static final String TAG = "CarSelectPassengerFrag";

    private static final int RECYCLER_VIEW_ADD_DURATION = 180;
    private static final int LOADER_MANAGER_ID = 12;

    //widgets
    @BindView(R.id.qce_car_select_passenger_search)
    QuicklyClearEditText mPassengerSearchQce;

    @BindView(R.id.recycler_car_select_passenger)
    RecyclerView mSelectPassengerRecycler;

    @BindView(R.id.tv_center_index)
    TextView mCenterIndex;

    @BindView(R.id.qib)
    QuickIndexBar mIndexBar;
    //arguments

    @Inject
    AlphabetSearchPresenter<CarSelectPassengerEntity> mAlphabetSearchPresenter;


    private CarSelectPassengerAdapter mCarSelectPassengerAdapter;
    private List<CarSelectPassengerEntity> mCarSelectPassengerEntityList = new ArrayList<>();


    public CarSelectPassengerFragment() {
        // Required empty public constructor
    }

    public static CarSelectPassengerFragment newInstance() {
        CarSelectPassengerFragment fragment = new CarSelectPassengerFragment();

        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mAlphabetSearchPresenter.attachView(this);
        initializeRecyclerView();
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIndexBar.setOnIndexChangeListener(new MyOnIndexChangeListener());
        if (PermissionHelper.checkReadContactPermission(mActivity)) {
            initializeContacts();
        } else {
            PermissionHelper.takeReadContactPermission(this, PermissionHelper.REQUEST_CODE_READ_CONTACT);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        setupToolBar();
    }


    private void initializeRecyclerView() {
        mCarSelectPassengerAdapter = new CarSelectPassengerAdapter(
                mActivity,
                mCarSelectPassengerEntityList
        );

        mSelectPassengerRecycler.setLayoutManager(new LinearLayoutManager(mActivity));
        mSelectPassengerRecycler.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f)));
        mSelectPassengerRecycler.getItemAnimator().setAddDuration(RECYCLER_VIEW_ADD_DURATION);
        mSelectPassengerRecycler.setAdapter(mCarSelectPassengerAdapter);
    }

    private void initializeContacts() {
        LoaderManager loaderManager = getLoaderManager();
        loaderManager.initLoader(LOADER_MANAGER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {
            @Override
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                return new CursorLoader(mActivity, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            }

            @Override
            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                HashMap<String, List<CarSelectPassengerEntity>> alphabetMap = new HashMap<>();
                while (data.moveToNext()) {
                    String name = data.getString(data.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String mobileNumber = data.getString(data.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER))
                            .replace(" ", "");
                    CarSelectPassengerEntity passengerEntity = new CarSelectPassengerEntity(name, mobileNumber);
                    AlphabetHelper.mobileContactHandler(alphabetMap, passengerEntity);
                }
                mAlphabetSearchPresenter.setAlphabetMap(alphabetMap);
                mCarSelectPassengerEntityList = AlphabetHelper.getCarAlphabetData(alphabetMap);

                mAlphabetSearchPresenter.setSearchEntityList(mCarSelectPassengerEntityList);
                mCarSelectPassengerAdapter.notifyOriginalData(mCarSelectPassengerEntityList);
            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
            }
        });
    }


    @OnTextChanged(R.id.qce_car_select_passenger_search)
    public void searchInputTextChange(CharSequence text) {
        int length = text.length();
        if (length <= 0) {
            mCarSelectPassengerAdapter.returnOriginal();
        } else {
            mAlphabetSearchPresenter.search(text.toString());
        }
    }

    @Override
    public void renderAlphabetSearchResult(List<CarSelectPassengerEntity> searchEntityList) {
        mCarSelectPassengerAdapter.notifyData(searchEntityList);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length > 0) {
            switch (requestCode) {
                case PermissionHelper.REQUEST_CODE_READ_CONTACT:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        initializeContacts();
                    }

            }
        }
    }

    @Override
    protected void initializeInjector() {
        DaggerOfficialCarComponent
                .builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_car_select_passenger;
    }

    @Override
    protected void setupToolBar() {
        ((CallCarForOthersActivity) mActivity).setToolbarTitle(R.string.title_select_passengers);
    }

    private class MyOnIndexChangeListener implements QuickIndexBar.OnIndexChangeListener {
        @Override
        public void onIndexChange(String selectAlphabet) {
            mCenterIndex.setText(selectAlphabet);
            mCenterIndex.setVisibility(View.VISIBLE);
            int indexOf = mCarSelectPassengerEntityList.indexOf(new CarSelectPassengerEntity(selectAlphabet));
            if (indexOf >= 0) {
                if (mSelectPassengerRecycler != null) {
                    mSelectPassengerRecycler.scrollToPosition(indexOf);
                }
            }
        }

        @Override
        public void onActionUp() {
            mCenterIndex.setVisibility(View.GONE);
        }
    }

}
